using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Diagnostics;

namespace BizTalk.BuildGenerator.Tasks.Tests
{
    /// <remarks />
    [TestClass]
    public abstract class MSBuildTest
    {        
        /// <remarks />
        private static readonly string MSBuildPath = Environment.ExpandEnvironmentVariables(@"%systemdrive%\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe");

        /// <remarks />
        protected static int RunMSBuild(string msbuildExeArguments)
        {
            var directoryInfo = new DirectoryInfo(".");
            return RunMSBuild(msbuildExeArguments, directoryInfo.FullName);
        }

        /// <remarks />
        protected static int RunMSBuild(string msbuildExeArguments, string workingDirectory)
        {
            var processStartInfo = new ProcessStartInfo(MSBuildPath, msbuildExeArguments)
                                       {
                                           CreateNoWindow = true,
                                           RedirectStandardError = true,
                                           RedirectStandardOutput = true,
                                           UseShellExecute = false,
                                           WorkingDirectory = workingDirectory
                                       };
            Trace.WriteLine(processStartInfo.FileName);
            var process = Process.Start(processStartInfo);
            Console.WriteLine(process.StandardOutput.ReadToEnd());
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                Console.WriteLine(process.StandardError.ReadToEnd());
            }
            return process.ExitCode;
        }

        /// <remarks />
        protected void GetFileAndWriteToPath(string fileResourceName, string filePathToBeWrittenTo)
        {
            var resourceStream = GetType().Assembly.GetManifestResourceStream(fileResourceName);
            if (resourceStream != null)
                using (var sr = new StreamReader(resourceStream))
                {
                    using (var sw = new StreamWriter(filePathToBeWrittenTo))
                    {
                        while (sr.Peek() >= 0)
                        {
                            sw.WriteLine(sr.ReadLine());
                        }
                        sw.Flush();
                    }
                }
        }
    }
}

